package com.lzw.main;

import com.lzw.app.ServerApp;
import com.lzw.data.AppRepository;
import com.lzw.utils.LogUtils;

/**
 * 清理无效服务线程
 * @author LZW
 */
public class ClearThread implements Runnable {
    private ServerApp serverApp;
    private int interval;

    public ClearThread(ServerApp serverApp, int interval) {
        this.interval = interval;
        this.serverApp = serverApp;
    }

    public void run() {
        while (true) {
            try {
                Thread.sleep(interval * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            doClear();
        }
    }

    private void doClear() {
        AppRepository appRepository = serverApp.getAppRepository();
        AppRepository serverRepository = serverApp.getServerRepository();
        clearRepository(appRepository);
        StringBuilder sb = new StringBuilder();
        LogUtils.printLogClear("服务注册", sb);
        System.out.println(sb.toString());
        clearRepository(serverRepository);
        sb = new StringBuilder();
        LogUtils.printLogClear("集群注册", sb);
        System.out.println(sb.toString());
    }

    private void clearRepository(AppRepository repository) {
        repository.cleatInstance();
    }
}
